﻿using System;
using System.Linq;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Daemon.Stages;
using JetBrains.ReSharper.Daemon.Xml.Highlightings;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.Psi.Xml;
using JetBrains.ReSharper.Psi.Xml.Tree;
using SPCAFContrib.ReSharper.Common;
using SPCAFContrib.ReSharper.Common.Attributes;
using SPCAFContrib.ReSharper.Common.Extensions;
using SPCAFContrib.ReSharper.Common.XmlAnalysis;
using SPCAFContrib.ReSharper.Consts;
using SPCAFContrib.ReSharper.Inspection.Xml.SPCAF;

[assembly: RegisterConfigurableSeverity(SPC012201Highlighting.CheckId,
  null,
  Consts.SPCAF_CORRECTNESS_GROUP,
  SPC012201Highlighting.CheckId + ": " + SPC012201Highlighting.Message,
  "Required fields Filterable, ParentType, Sortable, TypeDisplayName and TypeName must be declared in FieldType.",
  Severity.ERROR,
  false, Internal = false)]

namespace SPCAFContrib.ReSharper.Inspection.Xml.SPCAF
{
    [Applicability(
        IDEProjectType.SP2010FarmSolution |
        IDEProjectType.SPSandbox |
        IDEProjectType.SP2013FarmSolution)]
    public class DeclareRequiredAttributesInFieldType : XmlTagProblemAnalyzer
    {
        public override void Run(IXmlTag element, IHighlightingConsumer consumer)
        {
            if (element.GetProject().IsApplicableFor(this))
            {
                if (IsInvalid(element))
                {
                    SPC012201Highlighting errorHighlighting = new SPC012201Highlighting(element);
                    consumer.ConsumeHighlighting(element.Header.GetDocumentRange(), errorHighlighting);
                }
            }
        }

        public bool IsInvalid(IXmlTag element)
        {
            bool result = false;
            
            if (element.Header.ContainerName == "FieldType")
            {
                var tags = element.GetNestedTags<IXmlTag>("Field");
                result =
                    !(tags.Any(
                        t =>
                            t.CheckAttributeValue("Name",
                                new[] {"TypeName", "ParentType", "TypeDisplayName", "Sortable", "Filterable"}, true))
                        );
            }

            return result;
        }
    }

    [ConfigurableSeverityHighlighting(CheckId, XmlLanguage.Name, OverlapResolve = OverlapResolveKind.NONE, ShowToolTipInStatusBar = true)]
    public class SPC012201Highlighting : XmlErrorHighlighting
    {
        public const string CheckId = "SPC012201";
        public const string Message = "Declare required fields in FieldType";

        public IXmlTag Element { get; private set; }

        public SPC012201Highlighting(IXmlTag element) :
            base(String.Format("{0}: {1}", CheckId, Message))
        {
            Element = element;
        }
    }
}
